//
//  DetailSongListViewController.m
//  LastTemp
//
//  Created by dllo on 15/4/22.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "DetailSongListViewController.h"
#import "songListView.h"
#import "detailModel.h"
#import "DetailCell.h"
#import "NetWorkingTool.h"
#import "UIImageView+WebCache.h"
#import "AVSingleton.h"
#import "MJRefresh.h"
#import "BassModel.h"
#import "bofangViewController.h"
@interface DetailSongListViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UITableView *detailTableView;
@property(nonatomic, retain)NSMutableArray *detailArr;
@property(nonatomic, retain)NSNumber *count;
@property(nonatomic, assign)int page;
@property(nonatomic, retain)NSMutableArray *passPlayArr;
@property(nonatomic, retain)UIActivityIndicatorView *activity;
@end

@implementation DetailSongListViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.detailArr = [NSMutableArray array];
                self.title = @"分类";
    }
    return self;
}
- (void)dealloc
{
    [_detailArr release];
    [_detailTableView release];
    [_count release];
    [_passPlayArr release];
    [_activity release];
    [super dealloc];
}
// 解析数据
- (void)detailData{
    if ([AVSingleton shareSingleton].internetNum == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您现在没有网络,请检查网络!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        [alert release];
    } else {
    NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/channel/channel/%@/songs?size=50&page=1&app=ttpod&v=v7.7.0.2015012818&uid=&mid=iPhone5C&f=f320&s=s310&imsi=&hid=&splus=8.0.2&active=1&net=2&openudid=50a40f05044a0e2462e11cbf7d6612844b6c0008&idfa=058C286B-AB2C-41E2-A7FE-B67B3496FBBC&utdid=VQKI/UR603ADANyHaLs5uRrS&alf=201200", self.passSonglist_id];
//    NSLog(@"%@", self.passSonglist_id);
//    NSLog(@"%@", str);
    [NetWorkingTool netWorkingToolStr:str block:^(id result) {
        NSMutableDictionary *dic = result;
        NSMutableArray *arr = [NSMutableArray array];
        arr = dic[@"data"];
        self.count = dic[@"pageCount"];
        for (NSInteger i = 0; i < arr.count; i++) {
            NSMutableDictionary *dicNew = [NSMutableDictionary dictionary];
            dicNew = arr[i];
            detailModel *detailM = [[detailModel alloc] init];
            [detailM setValuesForKeysWithDictionary:dicNew];
            detailM.url = [dicNew[@"auditionList"] firstObject][@"url"];
            detailM.pageCount = dic[@"pageCount"];
            [self.detailArr addObject:detailM];
            [detailM release];
        }
        [self.detailTableView reloadData];
        [self.activity stopAnimating];
    }];
    }
}
// 加载数据
- (void)reloadNewData{
    if ([AVSingleton shareSingleton].internetNum == 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您现在没有网络,请检查网络!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        [alert release];
    } else {
//    static int page = 1;
    ++self.page;
    NSNumber *num = [NSNumber numberWithInt:self.page];
    if (num <= self.count) {
        
        NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/channel/channel/%@/songs?size=50&page=%d&app=ttpod&v=v7.7.0.2015012818&uid=&mid=iPhone5C&f=f320&s=s310&imsi=&hid=&splus=8.0.2&active=1&net=2&openudid=50a40f05044a0e2462e11cbf7d6612844b6c0008&idfa=058C286B-AB2C-41E2-A7FE-B67B3496FBBC&utdid=VQKI/UR603ADANyHaLs5uRrS&alf=201200", self.passSonglist_id, self.page];
        [NetWorkingTool netWorkingToolStr:str block:^(id result) {
            NSMutableDictionary *dic = result;
            NSMutableArray *arr = [NSMutableArray array];
            arr = dic[@"data"];
            for (NSInteger i = 0; i < arr.count; i++) {
                NSMutableDictionary *dicNew = [NSMutableDictionary dictionary];
                dicNew = arr[i];
                detailModel *detailM = [[detailModel alloc] init];
                [detailM setValuesForKeysWithDictionary:dicNew];
                detailM.url = [dicNew[@"auditionList"] firstObject][@"url"];
                detailM.pageCount = dic[@"pageCount"];
                [self.detailArr addObject:detailM];
                [detailM release];
            }
            [self.detailTableView reloadData];
        }];
        [self.detailTableView footerEndRefreshing];
    }
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"39"]];
    
    // 调用解析数据的方法, 开始解析数据
    [self detailData];
    
    // 顶部View
    songListView *songLV = [[songListView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 150)];
    songLV.layer.cornerRadius = 10;
    NSURL *url = [NSURL URLWithString:self.passSmall_pic_url];
    [songLV.picImageView sd_setImageWithURL:url];
    songLV.songlist_nameLabel.text = self.passSonglist_name;
    songLV.quantityLabel.text = [NSString stringWithFormat:@"%@首歌曲", self.passQuantity];
    [self.view addSubview:songLV];
    [songLV release];
    
    // 中下部TableView
    self.detailTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 214, self.view.frame.size.width, self.view.frame.size.height - 214) style:UITableViewStylePlain];
    [self.view addSubview:self.detailTableView];
    [_detailTableView release];
    self.detailTableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"39"]];
    
    self.detailTableView.delegate = self;
    self.detailTableView.dataSource = self;

    [self.detailTableView addFooterWithCallback:^{
        NSNumber *num = [NSNumber numberWithInt:1];
        if (self.count > num) {
            [self reloadNewData];
        }
    }];
    
    // 右button
////    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"player" style:UIBarButtonItemStylePlain target:self action:@selector(clickRightButton:)];
//    UIButton *RightButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    RightButton.frame = CGRectMake(0, 0, 54, 54);
//    [RightButton setBackgroundImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];
//    //    [RightButton setBackgroundImage:[UIImage imageNamed:@"dd"] forState:UIControlStateNormal];
//    [RightButton addTarget:self action:@selector(clickRightButton:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:RightButton] autorelease];
    
    // 进度轮
    self.activity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [self.activity setCenter:CGPointMake(self.view.frame.size.width / 2, (self.view.frame.size.height - 113) / 2)]; // 指定进度轮中心点
    [self.activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:self.activity];
    [self.activity startAnimating];
    [_activity release];
}
#pragma mark 右button点击方法
- (void)clickRightButton:(UIBarButtonItem *)button{
    bofangViewController *playVC = [[bofangViewController alloc] init];
    playVC.allArr = [AVSingleton shareSingleton].fromArr;
    [self presentViewController:playVC animated:YES completion:^{
    }];
    [playVC release];
}
//#pragma mark 右button点击方法
//- (void)clickRightButton:(UIBarButtonItem *)button{
//    bofangViewController *playVC = [[bofangViewController alloc] init];
//    playVC.allArr = [AVSingleton shareSingleton].fromArr;
//    [self presentViewController:playVC animated:YES completion:^{
//    }];
//    [playVC release];
//}

// 协议必须实现的两个方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.detailArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *reuse = @"reuse";
    DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[[DetailCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    detailModel *detailM = [[detailModel alloc] init];
    detailM = self.detailArr[indexPath.row];
    NSString *str = [NSString stringWithFormat:@"No%ld. %@", indexPath.row + 1, detailM.name];
    cell.nameLabel.text = str;
    cell.singerNameLabel.text = detailM.singerName;
    cell.detailImageView.image = [UIImage imageNamed:@"02"];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.passPlayArr = [NSMutableArray array];

    // 播放音乐
    detailModel *detailM =  self.detailArr[indexPath.row];
    if ([AVSingleton shareSingleton].fromNum != indexPath.row || [AVSingleton shareSingleton].fromNum != 0) {
        [[AFSoundManager sharedManager] stop];
    }
    [[AFSoundManager sharedManager] startStreamingRemoteAudioFromURL:detailM.url andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
        [AVSingleton shareSingleton].percentage = percentage;
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"mm:ss"];
        NSDate *elapsedTimeDate = [NSDate dateWithTimeIntervalSince1970:elapsedTime];
        [AVSingleton shareSingleton].beginTime = [formatter stringFromDate:elapsedTimeDate];
        
        NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSince1970:timeRemaining];
        [AVSingleton shareSingleton].time = [formatter stringFromDate:timeRemainingDate];
        
        
    }];

    // 通过基类model传值给播放界面
        for (NSInteger i = 0; i < self.detailArr.count; i++) {
            detailModel *detailM1 = self.detailArr[i];
            BassModel *baseModel = [[BassModel alloc] init];
            baseModel.name1 = detailM1.name;
            baseModel.singerName1 = detailM1.singerName;
            baseModel.url1 = detailM1.url;
            [self.passPlayArr addObject:baseModel];
            [baseModel release];
        }
        [AVSingleton shareSingleton].fromArr = self.passPlayArr;
    [AVSingleton shareSingleton].fromNum = indexPath.row;
    bofangViewController *play = [[bofangViewController alloc] init];
    [self presentViewController:play animated:YES completion:^{
        
    }];
    [AVSingleton shareSingleton].fromNum = indexPath.row;
    [AVSingleton shareSingleton].fromArr = self.passPlayArr;
    [AVSingleton shareSingleton].myBool = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
